package com.cswangdao.aspect;

import com.cswangdao.annotation.OperationLog;
import com.cswangdao.domain.model.MarketLog;
import com.cswangdao.mapper.MarketLogMapper;
import com.cswangdao.utils.ResponseMineUtil;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;


@Component
@Aspect
@Slf4j
public class OperationRecord {



    @Autowired
    private MarketLogMapper logMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(com.cswangdao.annotation.OperationLog)")
    public void operationLog() {}

    @AfterReturning(pointcut = "operationLog()")
    public void operationRecordByAround(JoinPoint joinPoint)  {

        getMarketLog(joinPoint,true);
    }

    @AfterThrowing(pointcut = "operationLog()")
    public void operationRecordByAfterThrowing(JoinPoint joinPoint) {
        getMarketLog(joinPoint,false);
        ResponseMineUtil.error(response);
    }

    private void getMarketLog(JoinPoint joinPoint,boolean isSuccessful) {
        MarketLog marketLog = new MarketLog();
        String url = request.getRequestURL().toString();
        String[] split = url.split("/");
        marketLog.setIp(split[2]);
        marketLog.setAdmin(request.getSession().getAttribute("username").toString());
        marketLog.setAddTime(new Date());
        marketLog.setUpdateTime(new Date());
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        boolean flag = method.isAnnotationPresent(OperationLog.class);
        if (flag) {
            OperationLog operationLog = method.getAnnotation(OperationLog.class);
            String action = operationLog.value();
            int type = operationLog.type();
            marketLog.setAction(action);
            marketLog.setType(type);
        }
        marketLog.setStatus(isSuccessful);
        if(isSuccessful){
            marketLog.setResult("成功");
        }else {
            marketLog.setResult("失败");
        }
        logMapper.addLog(marketLog);
    }


}
